package com.egao.platform.system.controller;

import com.egao.platform.common.core.JsonResult;
import com.egao.platform.common.utils.FileUploadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.wf.jwtp.annotation.Ignore;

import javax.servlet.http.HttpServletResponse;

/**
 * 文件服务器
 * Created by wangfan on 2018-12-24 16:10
 */
@Api(tags = "文件管理")
@RestController
@RequestMapping("/api/file")
public class FileController {

    @ApiOperation("上传文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "file", required = true, dataType = "_file")
    })
    @PostMapping("/upload")
    public JsonResult upload(@RequestParam MultipartFile file) {
        return FileUploadUtil.upload(file);
    }

    @ApiOperation("上传base64文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "base64", value = "base64", required = true, dataType = "string")
    })
    @PostMapping("/upload/base64")
    public JsonResult uploadBase64(String base64) {
        return FileUploadUtil.upload(base64);
    }

    @Ignore
    @ApiOperation("预览文件")
    @GetMapping("/{dir}/{name:.+}")
    public void file(@PathVariable("dir") String dir, @PathVariable("name") String name, HttpServletResponse response) {
        FileUploadUtil.preview(dir + "/" + name, response);
    }

    @Ignore
    @ApiOperation("下载文件")
    @GetMapping("/download/{dir}/{name:.+}")
    public void downloadFile(@PathVariable("dir") String dir, @PathVariable("name") String name, HttpServletResponse response) {
        FileUploadUtil.download(dir + "/" + name, response);
    }

    @Ignore
    @ApiOperation("查看缩略图")
    @GetMapping("/thumbnail/{dir}/{name:.+}")
    public void smFile(@PathVariable("dir") String dir, @PathVariable("name") String name, HttpServletResponse response) {
        FileUploadUtil.thumbnail(dir + "/" + name, response);
    }

    @ApiOperation("删除文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "path", value = "path", required = true, dataType = "string")
    })
    @DeleteMapping("/del")
    public JsonResult del(String path) {
        if (path == null || path.trim().isEmpty()) {
            return JsonResult.error("参数不能为空");
        }
        if (FileUploadUtil.delete(path)) {
            return JsonResult.ok("删除成功");
        }
        return JsonResult.error("删除失败");
    }

}
